package docxtoexcel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.List;

public class ExcelUtil {

    public static void main(String[] args) throws IOException {
        // 文件名称
        File file = new File("E:\\job\\tmp\\性能无线API字段清单0223.xlsx");
//         File file = new File("test/read.xlsx");
        // 根据文件名称获取操作工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
        // 获取读取的工作表，这里有两种方式
        Sheet sheet = workbook.getSheetAt(0);
//        Sheet sheet = workbook.getSheetAt(0);
        int allRow = sheet.getLastRowNum();   // 获取行数
        System.out.println(allRow);
        Row row = sheet.createRow(allRow);
        Cell cell = row.createCell(0);
        cell.setCellValue("abc");
        workbook.write(new FileOutputStream(file));
        // 按行读取数据
        /*for (int i = 0; i <= allRow; i++) {
            Row row = sheet.getRow(i);
            // 获取列数
            short lastCellNum = row.getLastCellNum();
            for (int j = 0; j < lastCellNum; j++) {
                String cellValue = row.getCell(j).getStringCellValue();
            }
        }*/
    }

    public static void write(List<InterfaceRow> interfaceRows) throws IOException {
        // 文件名称
        File file = new File("E:\\job\\tmp\\性能无线API字段清单0223.xlsx");
//         File file = new File("test/read.xlsx");
        // 根据文件名称获取操作工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
        // 获取读取的工作表，这里有两种方式
        Sheet sheet = workbook.getSheetAt(0);
//        Sheet sheet = workbook.getSheetAt(0);
        int allRow = sheet.getLastRowNum() + 1;   // 获取行数
        System.out.println(allRow);
        int index = allRow;
        for (int i = 0; i < interfaceRows.size(); i++, index++) {
            if (i == 0 || !interfaceRows.get(i).getApiCode().equals(interfaceRows.get(i - 1).getApiCode())) {
                index++;
            }
            Row row = sheet.createRow(index);
            row.createCell(0).setCellValue(interfaceRows.get(i).getApiCode());
            row.createCell(1).setCellValue(interfaceRows.get(i).getApiDescription());
            row.createCell(2).setCellValue(interfaceRows.get(i).getParamType());
            row.createCell(3).setCellValue(interfaceRows.get(i).getParamCode());
            row.createCell(4).setCellValue(interfaceRows.get(i).getIsRequired());
            row.createCell(5).setCellValue(interfaceRows.get(i).getParamDescription());
            row.createCell(6).setCellValue(interfaceRows.get(i).getDataType());
        }

        workbook.write(new FileOutputStream(file));
    }
}
